package com.xm2.demo.system.customer.service;

import com.xm2.demo.model.Complaint;
import com.xm2.demo.system.customer.dao.ComplaintRepository;
import com.xm2.demo.system.customer.ov.ComplaintOv;
import com.xm2.demo.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author
 * @Date 2018/12/16 15:51
 * @Description
 */
@Service("complaintService")
public class ComplaintServiceImpl implements ComplaintService {
    @Autowired
    private ComplaintRepository complaintRepository;

    @Override
    public Pagination findByComplaintPage(ComplaintOv complaintOv) {
        if (complaintOv.getStatus() != null) {
            complaintOv.setTotalRows(complaintRepository.findByStatus(complaintOv.getStatus()).size());
            Pageable pageable = new PageRequest(complaintOv.getCurrentPage(), complaintOv.getSize(), Sort.Direction.ASC, "id");
            complaintOv.setList(complaintRepository.findByStatus(complaintOv.getStatus(),pageable));
        } else {
            complaintOv.setTotalRows(complaintRepository.findAll().size());
            Pageable pageable = new PageRequest(complaintOv.getCurrentPage(), complaintOv.getSize(), Sort.Direction.ASC, "id");
            complaintOv.setList(complaintRepository.findAll(pageable).getContent());
        }
        return complaintOv;
    }

    @Override
    public Pagination findByComplaintPageDate(ComplaintOv complaintOv) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        complaintOv.setTotalRows(complaintRepository.findByDatePagination(dateFormat.parse(complaintOv.getStartDate()),dateFormat.parse(complaintOv.getStopDate())).size());
        complaintOv.setList(complaintRepository.findByDatePaginationLimit(dateFormat.parse(complaintOv.getStartDate()),dateFormat.parse(complaintOv.getStopDate()),complaintOv.getStartRow(),complaintOv.getSize()));
        return complaintOv;
    }

    @Override
    @Transactional
    public void updateComplaintStatus(ComplaintOv complaintOv) {
        complaintRepository.updateComplaintStatus(complaintOv.getId(),complaintOv.getStatus());
    }

    @Override
    public void deleteComplaintStatus(ComplaintOv complaintOv) {
        complaintRepository.delete(complaintOv.getId());
    }

    @Override
    public void addComplaint(Complaint complaint) {
        complaint.setDate(new Date());
        complaintRepository.save(complaint);
    }
}
